package com.leadbank.baselbf.outils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Environment;
import android.widget.Toast;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 通用工具类
 * @author yangli
 * @version 1.0.1.3
 * @since 2011-09-1 
 **/

public class Tools {

	/**
	 * 返回Manifest中app版本名
	 * @param  mthis
	 * @return String
	 * @author yangli
	 */
	public static String getLocalVerName(Context mthis){
		String str = "";
		PackageManager manager = mthis.getPackageManager();
		try {
			PackageInfo info = manager.getPackageInfo(mthis.getPackageName(), 0);
			str = info.versionName;   //版本名
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}	
		return str;
	}


	
	/**
	 * 返回Manifest中app包名
	 * @param  mthis
	 * @return String
	 * @author yangli
	 */
	public static String getPackageName(Context mthis){
		String str = "";
		PackageManager manager = mthis.getPackageManager();
		try {
			PackageInfo info = manager.getPackageInfo(mthis.getPackageName(), 0);
			str = info.packageName;  //包名
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	 
		return str;
	}
	
	/**
	 * 提示输出
	 * @param  mthis,str
	 */
	public static void showTip(Context mthis, String str) {
		Toast.makeText(mthis, str, Toast.LENGTH_LONG).show();
	}
	
	/**
	 * 是否有sd卡
	 * @author yangli
	 */
	public static boolean hasSdCard(){
		//DdUtil.log(android.os.Build.MODEL);
        String status=Environment.getExternalStorageState();   
        if(status.equals(Environment.MEDIA_MOUNTED)){   
            return true;   
        }   
        else {   
            return false;   
        }   
    }
	/**
	 * bmp保存到sd卡
	 * @param mthis
	 * @param path
	 * @param bitName
	 * @author yangli
	 */
	public static File saveBitmap(Context mthis,String path,String bitName,Bitmap bitmap) { 
		File file = null;
		try { 
			file = new File(path , bitName); 
			if (!file.exists()) {
				File file2 = new File(path); 
				file2.mkdirs();
			}
			file.createNewFile();
			FileOutputStream fOut = null; 
			if (hasSdCard()){
				fOut = new FileOutputStream(file); 
			} else {
				fOut = mthis.openFileOutput(bitName, mthis.MODE_PRIVATE);
			}
			if (bitmap!=null) {
				if (bitName.contains(".png") || bitName.contains(".PNG")) {
					bitmap.compress(Bitmap.CompressFormat.PNG, 90, fOut); 
				} else {
					bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fOut); 
				}
				fOut.flush(); 
			}
			if (fOut!=null) {
				fOut.close(); 
			}
		} catch (IOException e) { 
			e.printStackTrace(); 
		}
		return file;
	}
	
	/**
	 * 从网络获取图片
	 * @param url
	 * @return
	 * @author yangli
	 */
	public static Bitmap downloadBitmap(String url,String path,String imgName) {
		Bitmap bitmap = null;
		try {		
			URL uri = new URL(url);
			HttpURLConnection conn  = (HttpURLConnection) uri.openConnection();
			InputStream bis = conn.getInputStream();
			FilterInputStream fis= new FlushedInputStream(bis);
			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inJustDecodeBounds = false;
			long blen=conn.getContentLength();
			System.out.println(blen);
			if ( blen> 300000) {
				opts.inSampleSize = 8;
			} else if ( blen> 200000 && blen<=300000) {
				opts.inSampleSize = 6;
			} else if (blen > 100000 && blen<=200000) {
				opts.inSampleSize = 4;
			} else {
				opts.inSampleSize = 2;
			}
//			System.out.println("connection.getContentLength:"+connection.getContentLength());
//			System.out.println("opts:"+opts.inSampleSize);
			bitmap = BitmapFactory.decodeStream(fis,new Rect(),opts);
		} catch (OutOfMemoryError err) {
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
				bitmap = null;
			}
			return null;
		} catch (Exception e) {
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
				bitmap = null;
			}
			return null;
		}
    	return bitmap;
    }
	/**防止代码进行慢连接**/
	static class FlushedInputStream extends FilterInputStream {
		public FlushedInputStream(InputStream inputStream) {
			super(inputStream);
		}
		@Override
		public long skip(long n) throws IOException {
		    long totalBytesSkipped = 0L;
		    while (totalBytesSkipped < n) {
		        long bytesSkipped = in.skip(n - totalBytesSkipped);
		        if (bytesSkipped == 0L) {
		            int b = read();
		            if (b < 0) {
		                break;  // we reached EOF
		            } else {
		                bytesSkipped = 1; // we read one byte
		            }
		        }
		        totalBytesSkipped += bytesSkipped;
		    }
		    return totalBytesSkipped;
		}
	}
	
	/**
	 * 从本地读取图片 
	 * @param path
	 * @return
	 */
	public static Bitmap localBitmap(String path) {
		if (path == null || path.length() < 1)
			return null;
		Bitmap bitmap = null;
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = false;
		opts.inPurgeable = true;
		opts.inInputShareable=true;
		opts.inSampleSize = 4;
		try {
			synchronized (path) {
				InputStream is = new FileInputStream(path);
				bitmap = BitmapFactory.decodeStream(is, null, opts);
				//bitmap=BitmapFactory.decodeFile(path, opts);
			}
		} catch (OutOfMemoryError err) {
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
				bitmap = null;
			}
			return null;
	    } catch (Exception e) {
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
				bitmap = null;
			}
			return null;
	    }
		return bitmap;
	}

	/**
	 * 获取图片文件名
	 * @param url
	 * @return
	 */
	public static String getImageName(String url) {
		if(url==null || "".equals(url)){
			return "";
		}
		int indexOf = url.lastIndexOf("/") + 1;
		if (indexOf == 0) {
			return url;
		} else {
			String substring =url.length()+ url.substring(indexOf);
			return substring;
		}
	}
}
